import {
  delete_patient_guidance,
  delete_platform_guidance,
  patient_guidance_list,
  platform_guidance_list,
  reservation_guidance_list,
} from '@/services/guide';
import age from '@/utils/age';
import paging_fun from '@/utils/paging';
import { InfoCircleTwoTone, PlusOutlined } from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, Divider, message, Modal, Tabs, Tooltip } from 'antd';
import moment from 'moment';
import { useRef, useState } from 'react';
import AddInhospital from './components/AddInhospital';
import AppointmentDetails from './components/AppointmentDetails';
import EditInhospital from './components/EditInhospital';
import MemberDetails from './components/MemberDetails';
import RemoteDetails from './components/RemoteDetails';
import SetDoctor from './components/SetDoctor';
// import SetDoctor from './components/SetDoctor';
type GithubIssueItem = {
  id: number;
  phone: string;
  username: string;
  sex: string;
  plan_time: string;
  age: string;
  plan_at: string;
  id_card: string;
  birth: string;
  address: string;
  province: string;
  city: string;
  area: string;
  family_address: string;
};
const GuidePlan = () => {
  const actionRef = useRef<ActionType>();
  const actionRef1 = useRef<ActionType>();
  const actionRef2 = useRef<ActionType>();
  // 新增院内指导模态框状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 控制患者详情模态框的状态
  const [isMemberInfoModalOpen, setIsMemberInfoModalOpen] = useState(false);
  // 控制编辑院内指导模态框的状态
  const [isEditInhospital, setIsEditInhospital] = useState(false);
  // 存储编辑院内指导id
  const [inHospitalId, setInHospitalId] = useState<number>();
  // 存储院内指导患者id
  const [patientId, setPatientId] = useState<number>();
  // 控制院内指导删除模态框的状态
  const [delModalOpen, setDelModalOpen] = useState(false);
  // 存储删除院内指导id
  const [delId, setDelId] = useState();
  // 控制远程指导详情模态框的状态
  const [remoteModal, setRemoteModal] = useState(false);
  // 存储远程指导id
  const [remoteId, setRemoteId] = useState<number>();
  // 存储远程指导当前指导医生id
  const [remoteDoctor, setRemoteDoctor] = useState<any>([]);
  // 控制设置指导医生模态框的状态
  const [doctorModal, setDoctorModal] = useState(false);
  // 控制远程预约详情模态框
  const [appointmentModal, setAppointmentModal] = useState(false);
  // 存储远程预约指导id
  const [appointmentId, setAppointmentId] = useState<number>();
  // 控制远程预约删除模态框的状态
  const [remoteDelModal, setRemoteDelModal] = useState(false);

  // 控制新增院内指导模态框显示和隐藏
  const isShowModal = (show: boolean) => {
    setIsModalOpen(show);
  };
  // 控制编辑远程指导模态框的显示和隐藏
  const isShowEditInhospital = (status: boolean) => {
    setIsEditInhospital(status);
  };
  // 控制患者详情模态框显示和隐藏
  const isShowMemberInfoModal = (show: boolean) => {
    setIsMemberInfoModalOpen(show);
  };
  // 控制远程指导详情模态框的显示与隐藏
  const isShowRemoteModal = (status: boolean) => {
    setRemoteModal(status);
  };
  // 控制设置指导医生模态框的显示与隐藏
  const isShowDoctorModal = (status: boolean) => {
    setDoctorModal(status);
  };
  // 控制远程预约模态框的显示与隐藏
  const isShowAppointmentModal = (status: boolean) => {
    setAppointmentModal(status);
  };
  // 院内指导删除
  const isShowDelModal = (status: boolean) => {
    setDelModalOpen(status);
  };
  // 院内指导删除确认的回调
  const delOk = async () => {
    let res: any = await delete_patient_guidance({ id: delId });
    if (res.msg == 'ok') {
      actionRef.current?.reload();
      message.success('删除成功！');
      paging_fun(actionRef);
      setDelModalOpen(false);
    } else {
      message.error(res.msg);
    }
  };
  // 远程预约删除
  const isShowRemoteDel = (status: boolean) => {
    setRemoteDelModal(status);
  };
  // 远程预约删除确认的回调
  const remoteDelOk = async () => {
    let res: any = await delete_platform_guidance({ id: appointmentId });
    if (res.code == 200) {
      actionRef2.current?.reload();
      message.success('删除成功！');
      paging_fun(actionRef2);
      setRemoteDelModal(false);
    } else {
      message.error(res.msg);
    }
  };
  // 院内指导计划列表
  const get_popular_plan_list = async (params: {
    pageSize?: number | undefined;
    current?: number | undefined;
    keyword?: string | undefined;
  }) => {
    //默认分页参数和后端接口字段不匹配
    let request_body = {
      ...params,
      current: params.current,
      pageSize: params.pageSize,
      status: 0,
    };
    // console.log(params);
    const res = await patient_guidance_list(request_body);
    console.log('院内指导计划', res);
    return {
      data: res.data.list,
      success: true,
      total: res.data.total_count,
    };
  };
  // 远程指导计划列表
  const get_platform_guidance_list = async (params: {
    pageSize?: number | undefined;
    current?: number | undefined;
    keyword?: string | undefined;
  }) => {
    //默认分页参数和后端接口字段不匹配
    let request_body = {
      ...params,
      current: params.current,
      pageSize: params.pageSize,
    };
    const res = await platform_guidance_list(request_body);
    console.log('远程指导计划', res);
    return {
      data: res.data.list,
      success: true,
      total: res.data.total_count,
    };
  };
  // 远程指导计划列表
  const get_reservation_guidance_list = async (params: {
    pageSize?: number | undefined;
    current?: number | undefined;
    keyword?: string | undefined;
  }) => {
    //默认分页参数和后端接口字段不匹配
    let request_body = {
      ...params,
      current: params.current,
      pageSize: params.pageSize,
    };
    const res = await reservation_guidance_list(request_body);
    console.log('远程指导计划', res);
    return {
      data: res.data.list,
      success: true,
      total: res.data.total_count,
    };
  };

  // 切换tab
  const changeTab = (key: string) => {
    if (key == '院内指导') {
      actionRef.current?.reload();
    } else if (key == '远程指导') {
      actionRef1.current?.reload();
    } else if (key == '远程预约') {
      actionRef2.current?.reload();
    }
  };

  // 院内指导
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '患者账号',
      dataIndex: 'phone',
      align: 'center',
    },
    {
      title: '患者姓名',
      dataIndex: 'patient_name',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '患者姓名',
      dataIndex: 'name',
      hideInTable: true,
    },
    {
      title: '患者性别',
      dataIndex: 'sex',
      hideInSearch: true,
      align: 'center',
      valueEnum: {
        0: {
          text: '未知',
        },
        1: {
          text: '男',
        },
        2: {
          text: '女',
        },
      },
    },
    {
      title: '患者年龄',
      dataIndex: 'birth',
      hideInSearch: true,
      align: 'center',
      render: (_, record) => {
        return age(record.birth);
      },
    },
    {
      title: '身份证号',
      dataIndex: 'id_card',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '家庭住址',
      dataIndex: 'address',
      hideInSearch: true,
      align: 'center',
      render: (_, record) => {
        return record.province ? (
          <Tooltip title={record.province + record.city + record.area + record.family_address}>
            {(record.province + record.city + record.area + record.family_address).length > 10
              ? (record.province + record.city + record.area + record.family_address).substring(
                  0,
                  10,
                ) + '...'
              : record.province + record.city + record.area + record.family_address}
          </Tooltip>
        ) : (
          record.family_address
        );
      },
    },
    {
      title: '计划指导时间',
      dataIndex: 'plan_time',
      hideInSearch: true,
      align: 'center',
      render: (_, record) => {
        return moment(record.plan_time).format('YYYY-MM-DD');
      },
    },
    {
      title: '计划指导时间',
      dataIndex: 'plan_time',
      valueType: 'dateRange',
      colSize: 2,
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            start_date: value[0],
            end_date: value[1],
          };
        },
      },
    },
    {
      title: '指导医生',
      dataIndex: 'username',
      align: 'center',
    },
    {
      title: '操作',
      hideInSearch: true,
      align: 'center',
      render: (_: any, record: any) => (
        <>
          <Button
            key="info"
            type="link"
            onClick={() => {
              isShowMemberInfoModal(true);
              setPatientId(record.patient_id);
            }}
          >
            患者详情
          </Button>
          <Button
            key="editable"
            type="link"
            onClick={() => {
              isShowEditInhospital(true);
              setInHospitalId(record.id);
            }}
          >
            编辑
          </Button>
          <Button
            key="deltable"
            type="link"
            onClick={() => {
              isShowDelModal(true);
              setDelId(record.id);
            }}
          >
            删除
          </Button>
        </>
      ),
    },
  ];
  // 远程指导
  const columns1: ProColumns<GithubIssueItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '预约账号',
      dataIndex: 'phone',
      hideInTable: true,
      align: 'center',
    },
    {
      title: '机构名称',
      dataIndex: 'platform_name',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '机构名称',
      dataIndex: 'name',
      hideInTable: true,
      align: 'center',
    },
    {
      title: '预约账号',
      dataIndex: 'platform_phone',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '计划指导时间',
      dataIndex: 'plan_time',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '计划指导时间',
      dataIndex: 'plan_time',
      valueType: 'dateRange',
      colSize: 2,
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            start_date: value[0],
            end_date: value[1],
          };
        },
      },
    },
    {
      title: '指导医生',
      dataIndex: 'username',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '操作',
      hideInSearch: true,
      align: 'center',
      render: (_: any, record: any) => (
        <>
          <Button
            key="info"
            type="link"
            onClick={() => {
              setRemoteId(record.id);
              isShowRemoteModal(true);
            }}
          >
            详情
          </Button>
          <Button
            key="editable"
            type="link"
            onClick={() => {
              setRemoteId(record.id);
              setRemoteDoctor([record.guidance_user_id]);
              isShowDoctorModal(true);
            }}
          >
            设置指导医生
          </Button>
        </>
      ),
    },
  ];
  // 远程预约
  const columns2: ProColumns<GithubIssueItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '指导机构',
      dataIndex: 'name',
      hideInTable: true,
      align: 'center',
    },
    {
      title: '指导机构',
      dataIndex: 'platform_name',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '指导账号',
      dataIndex: 'platform_phone',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '指导医生',
      dataIndex: 'username',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '计划指导时间',
      dataIndex: 'plan_time',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '计划指导时间',
      dataIndex: 'plan_time',
      valueType: 'dateRange',
      colSize: 2,
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            start_date: value[0],
            end_date: value[1],
          };
        },
      },
    },

    {
      title: '操作',
      hideInSearch: true,
      align: 'center',
      render: (_: any, record: any) => (
        <>
          <Button
            key="detail"
            type="link"
            onClick={() => {
              setAppointmentId(record.id);
              isShowAppointmentModal(true);
            }}
          >
            详情
          </Button>
          <Button
            key="del"
            type="link"
            onClick={() => {
              setAppointmentId(record.id);
              isShowRemoteDel(true);
            }}
          >
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <PageContainer breadcrumb={false}>
      <Tabs
        defaultActiveKey="院内指导"
        onChange={changeTab}
        items={[
          {
            key: '院内指导',
            label: '院内指导',
            children: (
              <ProTable<GithubIssueItem>
                columns={columns}
                actionRef={actionRef}
                cardBordered
                request={async (params = {}) => get_popular_plan_list(params)}
                editable={{
                  type: 'multiple',
                }}
                rowKey={(record) => record.id}
                search={{
                  labelWidth: 'auto',
                  collapseRender: false,
                  collapsed: false,
                  span: 4,
                }}
                options={{
                  setting: {
                    listsHeight: 400,
                  },
                }}
                pagination={{
                  pageSize: 10,
                }}
                dateFormatter="string"
                headerTitle="院内指导计划表"
                toolBarRender={() => [
                  <Button
                    key="button"
                    icon={<PlusOutlined />}
                    type="primary"
                    onClick={() => isShowModal(true)}
                  >
                    新增
                  </Button>,
                ]}
              />
            ),
          },
          {
            key: '远程指导',
            label: '远程指导',
            children: (
              <ProTable<GithubIssueItem>
                columns={columns1}
                actionRef={actionRef1}
                cardBordered
                request={async (params = {}) => get_platform_guidance_list(params)}
                editable={{
                  type: 'multiple',
                }}
                rowKey={(record) => record.id}
                search={{
                  labelWidth: 'auto',
                  collapseRender: false,
                  collapsed: false,
                  span: 4,
                }}
                options={{
                  setting: {
                    listsHeight: 400,
                  },
                }}
                pagination={{
                  pageSize: 10,
                }}
                dateFormatter="string"
                headerTitle="远程指导计划表"
              />
            ),
          },
          {
            key: '远程预约',
            label: '远程预约',
            children: (
              <ProTable<GithubIssueItem>
                columns={columns2}
                actionRef={actionRef2}
                cardBordered
                request={async (params = {}) => get_reservation_guidance_list(params)}
                editable={{
                  type: 'multiple',
                }}
                rowKey={(record) => record.id}
                search={{
                  labelWidth: 'auto',
                  collapseRender: false,
                  collapsed: false,
                  span: 4,
                }}
                options={{
                  setting: {
                    listsHeight: 400,
                  },
                }}
                pagination={{
                  pageSize: 10,
                }}
                dateFormatter="string"
                headerTitle="远程预约计划表"
              />
            ),
          },
        ]}
      />
      {/* 新增院内指导 */}
      {isModalOpen ? (
        <AddInhospital
          isModalOpen={isModalOpen}
          isShowModal={isShowModal}
          actionRef={actionRef}
        ></AddInhospital>
      ) : (
        ''
      )}
      {/* 编辑院内指导 */}
      {isEditInhospital ? (
        <EditInhospital
          isShowEditInhospital={isShowEditInhospital}
          isEditInhospital={isEditInhospital}
          actionRef={actionRef}
          inHospitalId={inHospitalId}
        ></EditInhospital>
      ) : (
        ''
      )}
      {/* 患者详情 */}
      {isMemberInfoModalOpen ? (
        <MemberDetails
          isMemberInfoModalOpen={isMemberInfoModalOpen}
          isShowMemberInfoModal={isShowMemberInfoModal}
          patientId={patientId}
        ></MemberDetails>
      ) : (
        ''
      )}

      {/* 院内指导计划删除模态框 */}
      <Modal
        title="删除确认"
        open={delModalOpen}
        onOk={delOk}
        onCancel={() => isShowDelModal(false)}
      >
        <Divider />
        <p>
          <InfoCircleTwoTone twoToneColor="#ffcc00" /> 院内指导计划删除后无法恢复，确定要删除吗？
        </p>
      </Modal>
      {/* 远程指导详情 */}
      {remoteModal ? (
        <RemoteDetails
          remoteModal={remoteModal}
          remoteId={remoteId}
          isShowRemoteModal={isShowRemoteModal}
        ></RemoteDetails>
      ) : (
        ''
      )}
      {/* 设置指导医生 */}
      {doctorModal ? (
        <SetDoctor
          isShowDoctorModal={isShowDoctorModal}
          doctorModal={doctorModal}
          remoteId={remoteId}
          remoteDoctor={remoteDoctor}
          actionRef={actionRef1}
        ></SetDoctor>
      ) : (
        ''
      )}
      {/* 远程预约详情 */}
      {appointmentModal ? (
        <AppointmentDetails
          appointmentModal={appointmentModal}
          isShowAppointmentModal={isShowAppointmentModal}
          appointmentId={appointmentId}
        ></AppointmentDetails>
      ) : (
        ''
      )}
      {/* 远程预约计划删除模态框 */}
      <Modal
        title="删除确认"
        open={remoteDelModal}
        onOk={remoteDelOk}
        onCancel={() => isShowRemoteDel(false)}
      >
        <Divider />
        <p>
          <InfoCircleTwoTone twoToneColor="#ffcc00" /> 远程预约计划删除后无法恢复，确定要删除吗？
        </p>
      </Modal>
    </PageContainer>
  );
};
export default GuidePlan;
